package cn.zwx.activiti.example.controller;

import cn.hutool.core.util.IdcardUtil;
import cn.zwx.activiti.example.common.ResponseEntry;
import cn.zwx.activiti.example.common.enums.ErrorEnum;
import cn.zwx.activiti.example.common.exception.BizException;
import cn.zwx.activiti.example.model.req.CompleteTaskReq;
import cn.zwx.activiti.example.model.req.FormDataShowReq;
import cn.zwx.activiti.example.model.req.UserTaskImageReq;
import cn.zwx.activiti.example.model.req.UserTaskReq;
import cn.zwx.activiti.example.model.resp.FormDataShowResp;
import cn.zwx.activiti.example.model.resp.UserTaskResp;
import cn.zwx.activiti.example.service.UserTaskService;
import cn.zwx.activiti.example.utils.SecurityUtil;
import cn.zwx.activiti.example.utils.ValidatorUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.runtime.shared.query.Page;
import org.activiti.api.runtime.shared.query.Pageable;
import org.activiti.api.task.model.Task;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @description:
 * @projectName:activiti-example
 * @see:cn.zwx.activiti.example.controller
 * @author:zhangwenxue
 * @createTime:2021/6/2 21:11
 * @version:1.0
 */
@RestController
@RequestMapping("/task")
@Api(tags = "用户的任务")
public class UserTaskController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(UserTaskController.class);


    @Autowired
    private SecurityUtil securityUtil;

    @Autowired
    private UserTaskService userTaskService;

    /**
     * @description 获取我的代办任务
     * @return AjaxResponse
     * @author zhangwenxue
     * @createTime 2021/6/2 21:15
     **/
    @RequestMapping(value = "/getTasks",method = RequestMethod.POST)
    @ApiOperation("获取我的代办任务")
    public ResponseEntry<UserTaskResp> getTasks(@RequestBody UserTaskReq req) {
        // 验证参数
        securityUtil.logInAs(getUserName());
//        req.setUserName(getUserName());
        ValidatorUtils.getInstance().validateEntity(req);
        // 请求接口
        Page<UserTaskResp> page = userTaskService.getTasks(req);
        // 返回参数
        return ResponseEntry.ok(page);
    }

    /**
     * @description 渲染动态表单
     * @return AjaxResponse
     * @author zhangwenxue
     * @createTime 2021/6/2 21:15
     **/
    @RequestMapping(value = "/formDataShow",method = RequestMethod.POST)
    @ApiOperation("渲染动态表单")
    public ResponseEntry<FormDataShowResp> formDataShow(@RequestBody FormDataShowReq req) {
        // 验证参数
        securityUtil.logInAs(getUserName());
//        req.setUserName(getUserName());
        ValidatorUtils.getInstance().validateEntity(req);
        // 请求接口
        List<FormDataShowResp> respList = userTaskService.formDataShow(req);
        // 返回参数
        return ResponseEntry.ok(respList);
    }

    /**
     * @description 完成任务
     * @return AjaxResponse
     * @author zhangwenxue
     * @createTime 2021/6/2 21:15
     **/
    @RequestMapping(value = "/completeTask",method = RequestMethod.POST)
    @ApiOperation("完成任务")
    public ResponseEntry<Void> completeTask(@RequestBody CompleteTaskReq req) {
        // 验证参数
        securityUtil.logInAs(getUserName());
        ValidatorUtils.getInstance().validateEntity(req);
        // 请求接口
        userTaskService.completeTask(req);
        // 返回参数
        return ResponseEntry.ok();
    }


    /**
     * @description 查询任务流程图
     * @return AjaxResponse
     * @author zhangwenxue
     * @createTime 2021/6/2 21:15
     **/
    @RequestMapping(value = "/getTasks/image",method = RequestMethod.POST)
    @ApiOperation("查询任务流程图")
    public void getTasksImage(HttpServletResponse response,@RequestBody UserTaskImageReq req) {
        // 验证参数
        securityUtil.logInAs(getUserName());
        ValidatorUtils.getInstance().validateEntity(req);
        // 请求接口
        try {
            // 生成图片流
            InputStream in = userTaskService.getTasksImage(req);
            BufferedInputStream buffer_in = new BufferedInputStream(in);
            int count = buffer_in.available();
            byte[] bytes = new byte[count];
            // 写出去
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html");
            ServletOutputStream outputStream = response.getOutputStream();
            int len = 0;
            while ((len = buffer_in.read(bytes))!= -1){
                // 写出去
                outputStream.write(bytes,0,len);
            }
        }catch (Exception e){
            logger.error("查询任务流程图,异常",e);
            throw new BizException(ErrorEnum.TASKS_IMAGE_INSTANCE_FAILED.getErrorCode(),ErrorEnum.TASKS_IMAGE_INSTANCE_FAILED.getErrorMsg());
        }



    }

}
